<?php

namespace app\macht\controller;

use app\common\model\Agent;
use app\common\model\CardFans;
use app\common\model\CardFansGroupDict;
use app\common\model\CardMember;
use app\common\model\CardUserGet;
use app\common\model\CardGeneral;
use app\common\model\Momerchant;
use app\common\model\WxOpen;
use app\common\model\System;
use app\common\controller\AdminBase;

use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Wxfans extends MachBase
{
    //粉丝列表
    public function fanslist()
    {
        $CardFans = new CardFans();
        $CardGeneral = new CardGeneral();
        $CardMember = new CardMember();
        $Momerchant = new Momerchant();
        $CardFansGroupDict = new CardFansGroupDict();
        $p_data = request()->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            if ($p_data['nickname']) {
                $map['nickname'] = array('like', '%' . trim($p_data['nickname']) . '%');
            } else {
                $p_data['nickname'] = '';
            }
            if ($p_data['sex']) {
                $map['sex'] = array('eq', trim($p_data['sex']));
            } else {
                $p_data['sex'] = '';
            }
            if ($p_data['group']) {
                $map['group'] = $p_data['group'];
            } else {
                $p_data['group'] = '';
            }
            if ($p_data['group']) {
                $map['group'] = $p_data['group'];
            } else {
                $p_data['group'] = '';
            }
            if (!empty($p_data['search_date'])) {
                $date = explode(" - ", $p_data['search_date']);
                $start_time = strtotime($date[0]);
                $end_time = strtotime($date[1]);
                $map['create_time'] = array(array('egt', $start_time), array('elt', $end_time), 'and');
            }
        } else {
            $p_data['nickname'] = '';
            $p_data['sex'] = '';
            $p_data['group'] = '';
        }
        $map['wx_open_id'] = ['in', $this->get_open_id()];
        $mab['mid'] = ['in', $this->get_mer_mid()];
        $wechat['top_mid'] = Session::get('login_top_mid');

        $wechat['wx_open_id'] = $Momerchant->where('id', $wechat['top_mid'])->value('wx_open_id');

        $fanslist = $CardFans->where($map)->order('id desc')->paginate('15',false, ['query' => request()->param()]);
      
//        $cardus = $CardMember->where($mab)->select();
//        $cards = $CardGeneral->where($mab)->select();
        $grouplist = $CardFansGroupDict->where(['wx_open_id' => $wechat['wx_open_id']])->select();
        //粉丝统计
        $mag['wx_open_id'] = ['in', $this->get_open_id()];
//        var_dump($mag);
        $fans['sum'] = $CardFans->where($mag)->count('openid');
        $fans['sosum'] = $CardFans->where($map)->count('id');
        $this->assign('fans',$fans);
        $this->assign('grouplist', $grouplist);
        $this->assign('wechat', $wechat);
        $this->assign('p_data', $p_data);
        $this->assign('fanslist', $fanslist);
//        $this->assign('cards', $cards);
//        $this->assign('cardus', $cardus);
        return $this->fetch();
    }

    //分组设置
    public function setgroup()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardFans = new CardFans();
            $grou = explode(',', $arr['id']);
            foreach ($grou as $k => $v) {
                $data[$k]['id'] = $v;
                $data[$k]['group'] = $arr['group'];
            }
            $res = $CardFans->saveAll($data);
            if ($res) {
                $rdata['code'] = 0;
                $rdata['message'] = '设置成功';
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = '设置失败';
            }
            return json($rdata);
        }
    }

    //移出分组
    public function remgroup()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardFans = new CardFans();
            $data['id'] = explode(',', $arr['id']);
            $data['group'] = 0;
            $res = $CardFans->allowField(true)->saveAll($data);
            if ($res) {
                $rdata['code'] = 0;
                $rdata['message'] = '设置成功';
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = '设置失败';
            }
            return json($rdata);
        }
    }

    //分组列表
    public function listgroup()
    {
        if (Request()->isAjax()) {
            $Momerchant = new Momerchant();
            $CardFansGroupDict = new CardFansGroupDict();
            $top_mid = Session::get('login_top_mid');
            $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
            $grouplist = $CardFansGroupDict->where(['wx_open_id' => $wx_open_id])->select();
            if ($grouplist) {
                $rdata['code'] = 0;
                $rdata['data'] = $grouplist;
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = $CardFansGroupDict->getError();
            }
            return json($rdata);
        }
    }

    //添加分组
    public function addgroup()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
//            return json($arr);
            $data['wx_open_id'] = $arr['wx_open_id'];
            $data['group_name'] = $arr['group_name'];
            $data['top_mid'] = $arr['top_mid'];
            $data['create_time'] = time();
            $CardFansGroupDice = new CardFansGroupDict();
            $res = $CardFansGroupDice->save($data);
            if ($res) {
                $rdata['code'] = 0;
                $rdata['message'] = '添加成功';
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = '添加失败';
                $rdata['data'] = $data;
                $rdata['sql'] = $CardFansGroupDice->getLastSql();
            }
            return json($rdata);
        }
    }

    //修改
    public function editgroup()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardFansGroupDice = new CardFansGroupDict();
            $data['group_name'] = $arr['group_name'];
            $res = $CardFansGroupDice->allowField(true)->save($data, ['id' => $arr['id']]);
            if ($res) {
                $rdata['code'] = 0;
                $rdata['message'] = '修改成功';
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = '修改失败';
            }
            return json($rdata);
        }
    }

    //删除
    public function delgroup()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardFansGroupDice = new CardFansGroupDict();
            $res = $CardFansGroupDice->where(['id' => $arr['id']])->delete();
            if ($res) {
                $rdata['code'] = 0;
                $rdata['message'] = '删除成功';
            } else {
                $rdata['code'] = 9001;
                $rdata['message'] = '删除失败';
            }
            return json($rdata);
        }
    }


    //粉丝详情
    public function fansinfo()
    {
        $CardFans = new CardFans();
        $CardGeneral = new CardGeneral();
        $CardMember = new CardMember();
        $map['wx_open_id'] = ['in', $this->get_open_id()];
        $map['id'] = request()->get('id');
        $info = $CardFans->where($map)->find();
        $mab['statu'] = 0;
        $mab['mid'] = ['in', $this->get_mer_mid()];
        $mag['statu'] = 0;
        $mag['mid'] = ['in', $this->get_mer_mid()];
        $mag['end_timestamp'] = ['gt',time()];
        $cards = $CardGeneral->where($mag)->select();
        $cardus = $CardMember->where($mab)->select();
        $this->assign('cardus', $cardus);
        $this->assign('cards', $cards);
        $this->assign('info', $info);
        return $this->fetch();
    }

    //
    public function get_open_id()
    {
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $wx_open_id = $Momerchant->where('id', $top_mid)->value('wx_open_id');
        return $wx_open_id;
    }

    //同步微信粉丝列表（一次同步700人左右会失去响应）
    public function getfanslist()
    {
        $is_fans_syn = $this->isweeksynuser();
        if ($is_fans_syn == 0) {
            $option = $this->options();
            $wxObj = new Wxobjopen($option);
            $next_openid = '';
            $res = $wxObj->getUserList();
            //总数
            $total = $res['total'];
            //拉取数
            $count = $res['count'];
            //拉取列表
            $end_openid = $res['next_openid'];
            $openid_list = [];
            $openid_list = $res['data']['openid'];
            $WxOpen = new WxOpen();
            $wx_open_id = $this->get_open_id();
            $gh_id = $WxOpen->where('id', $wx_open_id)->value('gh_id');
            $e = 0;
            if (is_array($openid_list) && $openid_list !== '') {
                foreach ($openid_list as $k => $v) {
                    $sdata['type'] = "task_syn_fans";
                    $sdata['wx_open_id'] = $wx_open_id;
                    $sdata['gh_id'] = $gh_id;
                    $sdata['openid'][] = $v;
                    if ($k % 50 == 0) {
                        $ress = action('merchant/jobmach/task_syn_fans', array($sdata));
                        $sdata = [];
                        $e = $k;
                    }
                    if ($total - $e < 50) {
                        $ress = action('merchant/jobmach/task_syn_fans', array($sdata));
                        $sdata = [];
                    }
                }
                $this->success('一共' . $total . '粉丝，将在后台同步。', 'wxfans/fanslist');
            } else {
                $this->success('一共' . $total . '粉丝。', 'wxfans/fanslist');
            }
        }else{
            $this->error('您已在一周内同步过粉丝，一周内不可重复同步', 'wxfans/fanslist');
        }
    }

    //判断是否在一周内同步过会员
    /*
     * 并更新同步时间
     * */
    private function isweeksynuser(){
        $WxOpen = new WxOpen();
        $map['id'] = $this->get_open_id();
        $openinfo = $WxOpen->where($map)->find();
        $syn_fans_time = $openinfo['syn_fans_time'] + 86400*7;
        $time = time();
        if ($time > $syn_fans_time){
            $data['syn_fans_time'] = time();
            $WxOpen->allowField(true)->save($data,$map);
            $res = 0;
        }else{
            $res = 1;
        }
        return $res;
    }


    public function options()
    {
        Session::set('openid', null);
        $top_mid = Session::get('login_top_mid');
        $Momerchant = new Momerchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $momerchantinfo=$Momerchant->where('id', $top_mid)->field('wx_open_id,agent')->find();
        $wx_open_id = $momerchantinfo['wx_open_id'];
//        $config = $System->where(['id' => 1])->find();
        $config = $Agent->where(['id' => $momerchantinfo['agent']])->find();
        $users = $WxOpen->where(['id' => $wx_open_id])->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
